package com.base.myproject.client.ui.celleditor;

import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.ColumnInfo;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.ui.BaseGrid;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.FieldEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.util.BaseEventPreview;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.util.Rectangle;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.form.TriggerField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Element;

/**
 * 
 * 列表下拉，在form中使用
 * Grid中使用的办法是
 * GridEditor grideditor = new GridEditor(bge);
		serviceitem.setEditor(grideditor);
		
 * @author zgw 2009-6-14 下午10:51:34
 * @param <D>
 * 
 *            javazgw@gmail.com
 */
public class BaseGridEditor<D extends String> extends TriggerField<D> implements
		Listener<ComponentEvent>,FieldValue {

	protected BaseEventPreview focusPreview;
	final Window w = new Window();
	boolean b = false;
	List<ColumnConfig> columns = null;
	ModelType type = null;
	StoreInfo info = null;
	String returncolumn = null;
	BaseGrid<BusiObject> grid;
	BaseStore<BusiObject> basestore;
	BaseStore<BusiObject> target_store;
	ColumnInfo[] sourcecol;
	ColumnInfo[] target_col;
	public boolean isediting = false; //true 就是在编辑

	final Button yesbutton = new Button("确定");
	final Button button = new Button("取消");

	BaseGridEditor thiss;

	Object codevalue;
	Object displaynamevalue;
	String code;
	StoreFilterField<BusiObject> field ;
	Button reloadbutton = new Button("刷新");
	public BaseGridEditor(List<ColumnConfig> columns, ModelType type,
			StoreInfo info, String returncolumn) {
		super();
		this.setTriggerStyle("x-form-search-trigger");
		this.columns = columns;
		this.type = type;
		this.info = info;
		this.returncolumn = returncolumn;
		thiss = this;
		this.setEditable(false);
	}
	public BaseGridEditor(List<ColumnConfig> columns,BaseStore basestore,String returncolumn) {

		
		this(columns,basestore,returncolumn,null);
		
		
	}
	public BaseGridEditor(List<ColumnConfig> columns,BaseStore basestore,String returncolumn,String code) {
		super();
		this.setTriggerStyle("x-form-search-trigger");
		this.columns = columns;
//		this.type = type;
//		this.info = info;
		this.returncolumn = returncolumn;
		this.code = code;
		this.basestore = basestore;
		thiss = this;
		this.setEditable(false);
		
	}

	@Override
	protected void onRender(Element target, int index) {
		super.onRender(target, index);
		focusPreview = new BaseEventPreview();

		// setValue((D)"zzzz");
		// setRawValue("ggg");
	}

	@Override
	protected void onBlur(ComponentEvent ce) {
		Rectangle rec = trigger.getBounds();
		if (rec.contains(BaseEventPreview.getLastClientX(), BaseEventPreview
				.getLastClientY())) {
			ce.stopEvent();
			return;
		}
		super.onBlur(ce);
		focusPreview.remove();
	}

	@Override
	protected void onFocus(ComponentEvent ce) {
		super.onFocus(ce);
		focusPreview.add();
	}
	  private int lastKeyCode;
	protected void onKeyDown(FieldEvent fe) {
		super.onKeyPress(fe);
		lastKeyCode = fe.getKeyCode();

		if(lastKeyCode == KeyCodes.KEY_DELETE )
		{
			
			setValue(null);
			triggerBlur(null);
			
		}

		
	}
	

	  @Override
	  protected void onKeyPress(FieldEvent fe) {
		  super.onKeyPress(fe);
	    //char key = (char) fe.getKeyCode();
//	    System.out.println("lastKeyCode 2 = "+lastKeyCode);
//	    System.out.println("lastKeyCode 3 = "+ KeyCodes.KEY_DELETE);
	    if (fe.isSpecialKey(lastKeyCode) || lastKeyCode == KeyCodes.KEY_BACKSPACE
	        || lastKeyCode == KeyCodes.KEY_DELETE || fe.isControlKey()) {
	    	
	      return;
	    }
	    if (lastKeyCode == KeyCodes.KEY_ESCAPE) {
			w.hide();
		} else {
			showEditor();
		}
	
	    fe.stopEvent();
	  }

	@Override
	protected void onTriggerClick(ComponentEvent ce) {
		super.onTriggerClick(ce);
		// Info.display("Trigger Click", "TriggerClick is fired");
		
		showEditor();
	}

	private void showEditor() {
		if (!b) {
			initGrid();
			w.show();
			b = true;
		} else
		{
			grid.setHeight(380);
			w.show();
		
		}
		//w.focus();
		field.reset();
		field.focus();
		//field.setEmptyText("请录入信息进行快速查找");
		
		isediting = true;
	}

	public boolean isshow() {
		return w.isVisible();
	}

	public void initGrid() {

		w.setHeading("选择");
		
		w.setModal(true);
		w.setSize(400, 495);
		w.setMaximizable(true);
		// w.setToolTip("");
		// w.setUrl("http://www.163.com");
		focusPreview = new BaseEventPreview();
		//Rectangle rec = trigger.getBounds();

		//w.setPosition(rec.x - w.getInitialWidth(), rec.y + rec.height);

		// w.setLayout(new CenterLayout());

		// ---grid

		final CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		columns.add(0, cbs.getColumn());

		// ColumnConfig bcode = new ColumnConfig("bcode", "人员编码", 100);
		//			
		// columns.add(bcode);
		//
		// ColumnConfig bname = new ColumnConfig("bname", "人员名", 100);
		//			
		// columns.add(bname);

		ColumnModel cm = new ColumnModel(columns);

		// ModelType type = new ModelType();
		// type.root = "records";
		// type.recordName = "record";
		// type.addField("bcode");
		// type.addField("bname");
		//
		// StoreInfo info = new StoreInfo();
		// info.setTablename("bcode");
		// info.setSql("select bcode,bname from bcode");
		/**
		 * 直接传入store，不需要加载数据，
		 */
		if(type!=null)
		basestore = new BaseStore(type, info);
		grid = new BaseGrid(basestore, cm,false,false,null);
		grid.setAutoWidth(true);
		grid.setHeight(400);
		cbs.setSelectionMode(SelectionMode.MULTI);
		grid.setSelectionModel(cbs);
		
		// ---end grid
		ContentPanel bottompanel = new ContentPanel();
		bottompanel.setHeaderVisible(false);
		bottompanel.setLayout(new TableLayout(2));

		
		yesbutton.addListener(Events.Select, this);
		button.addListener(Events.Select, this);
		reloadbutton.addListener(Events.Select, this);
		// TableData t1 = new TableData();
		bottompanel.add(yesbutton);
		bottompanel.add(button);
		grid.setLoadMask(true);
		ContentPanel c = new ContentPanel();
		c.setHeaderVisible(false);
		//--加入过滤查找
		field = new StoreFilterField<BusiObject>() {
			@Override
			protected boolean doSelect(Store<BusiObject> store,
					BusiObject parent, BusiObject record, String property,
					String filter) {

			return	Select(store,parent,record,property,filter);
			}

			@Override
			protected void onFilter() {
				super.onFilter();

			
			}

		};
		
		field.setAutoWidth(true);
		field.setToolTip("对当前页面进行查找");
		field.bind(basestore);
		field.setFieldLabel("当页搜索");
		//--
		c.setLayout(new RowLayout(Orientation.VERTICAL));  
		
		ContentPanel cpanel = new ContentPanel();
		cpanel.setHeaderVisible(false);
		cpanel.setLayout(new RowLayout(Orientation.HORIZONTAL));
		reloadbutton.setToolTip("什么时候用此按钮？当你要选择的数据在别处被改变，点击刷新保持数据最新");
		if(this.type!=null)
		cpanel.add(field,new RowData(1, 1, new Margins(4)));
		
		cpanel.add(reloadbutton,new RowData(-1, 1, new Margins(4)));
		cpanel.setHeight(30);
		
		c.add(cpanel,new RowData(1, -1, new Margins(4)));
		c.add(grid,new RowData(1, 1, new Margins(4)));
		
		w.setScrollMode(Scroll.AUTO);
		w.add(c);
		w.addButton(yesbutton);
		w.addButton(button);
		// w.setBottomComponent(bottompanel);
		w.addListener(Events.Hide, this);
		w.show();
	}

	@Override
	public void setValue(D value) {

		super.setValue(value);
	}

	public void setRawValue(String text) {

		if (rendered) {

			getInputEl().setValue(text);
		}
	}

	public void dopost(final ModelData modeldata) {

		// store.setValue("qty", modeldata.get("qtyunit"));
		if(sourcecol!=null)
		for (int i = 0; i < sourcecol.length; i++) {
			
			Object o = modeldata.get(sourcecol[i].getName());
			switch (target_col[i].getType()) {
			case ColumnInfo.DOUBLE:
				target_store.setValue(target_col[i].getName(), 	Double.parseDouble(o==null?"0":o.toString()));
				break;
			case ColumnInfo.STRING:
				target_store.setValue(target_col[i].getName(), modeldata.get(sourcecol[i].getName()));
				break;
			case ColumnInfo.DATETIME:
				target_store.setValue(target_col[i].getName(), modeldata.get(sourcecol[i].getName()));
				break;
			default:
				target_store.setValue(target_col[i].getName(), modeldata.get(sourcecol[i].getName()));
				break;
			}


			//target_store.setValue(target_col[i], modeldata.get(sourcecol[i]));
		}
//		target_store.setValue("upric", new java.lang.Double("123"));
	}

	/**
	 * @return the target_store
	 */
	public BaseStore getTarget_store() {
		return target_store;
	}

	/**
	 * @param target_store
	 *            the target_store to set
	 */
	public void setTarget_store(BaseStore target_store) {
		this.target_store = target_store;
	}



	/**
	 * @return the sourcecol
	 */
	public ColumnInfo[] getSourcecol() {
		return sourcecol;
	}

	/**
	 * @param sourcecol the sourcecol to set
	 */
	public void setSourcecol(ColumnInfo[] sourcecol) {
		this.sourcecol = sourcecol;
	}

	/**
	 * @return the target_col
	 */
	public ColumnInfo[] getTarget_col() {
		return target_col;
	}

	/**
	 * 
	 * @param target_col the target_col to set
	 */
	public void setTarget_col(ColumnInfo[] target_col) {
		this.target_col = target_col;
	}

	@Override
	public void handleEvent(ComponentEvent be) {
		if (be.getType() == Events.Select ||be.getType() == Events.Hide) {
			
			if (be.getSource() == yesbutton) {

				setValue((D) basestore.getValue(returncolumn));

				if(code!=null)
				setCode(basestore.getValue(code));
				setDisplayname(basestore.getValue(returncolumn));
				
				if (sourcecol!=null && sourcecol.length > 0) {
					dopost(basestore.getAt(basestore.getCurcowindex()));
				}
				doposted(basestore.getAt(basestore.getCurcowindex()));
				
				isediting = false;
				w.hide();
				triggerBlur(null);
			} else if (be.getSource() == button) {

				isediting = false;
				w.hide();
				triggerBlur(null);
				// focus();
			}
			else if(be.getSource() == reloadbutton)
			{
				field.reset();
				basestore.reload();
			}
			
		}
		
		
		
		
	}
/**
 * 过滤方法，有特殊的方式之类可以重载
 * @param store
 * @param parent
 * @param record
 * @param property
 * @param filter
 * @return
 */
	protected boolean Select(Store<BusiObject> store,
			BusiObject parent, BusiObject record, String property,
			String filter) {
		for (int i = 0; i < type.getFieldCount(); i++) {

			Object name = record.get(type.getField(i).getName());
			
			//TODO
			if (name!=null&&(name.toString().indexOf(filter.toLowerCase()) != -1 || name.toString().indexOf(filter.toUpperCase()) != -1 )) {
				return true;
			}
		}
		return false;
	}
	/**
	 * 提交后处理，之类继承
	 * @param at
	 */
	public  void doposted(ModelData at) {
		
		
	}
	/**
	 * @return the basestore
	 */
	public BaseStore getBasestore() {
		return basestore;
	}

	/**
	 * @param basestore the basestore to set
	 */
	public void setBasestore(BaseStore basestore) {
		this.basestore = basestore;
	}
	@Override
	public Object getCode() {
		// TODO Auto-generated method stub
		return this.codevalue;
	}
	@Override
	public void setCode(Object code) {
		this.codevalue = code;
		
	}
	@Override
	public Object getDisplayname() {
		// TODO Auto-generated method stub
		return this.displaynamevalue;
	}
	
	@Override
	public void setDisplayname(Object displayname) {
		this.displaynamevalue = displayname;
		
	}


}